package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：seanyang
 * @date ：Created in 2019/7/22
 * @description ：
 * @version: 1.0
 */
public class SecurityUserDetailsService implements UserDetailsService {
	//依赖注入BCrypt
	@Autowired
	private BCryptPasswordEncoder passwordEncoder;
	//依赖注入userService
	@Reference
	private UserService userService;

	// 模拟数据库的用户记录，如下User类是health_common中的自定义实体类User
	// 修改Role、Permission，为其增加不带参、带参构造方法
	private static Map<String, User> userDb = new HashMap();
	static {
		User user1 = new User();
		user1.setUsername("admin");
		user1.setPassword("123");
		// 用户权限与角色
		Role role1 = new Role("系统管理员","ROLE_ADMIN");
		role1.getPermissions().add(new Permission("添加权限","add"));
		role1.getPermissions().add(new Permission("删除权限","delete"));
		role1.getPermissions().add(new Permission("更新权限","update"));
		role1.getPermissions().add(new Permission("查询权限","find"));
		user1.getRoles().add(role1);
		userDb.put(user1.getUsername(),user1);

		User userZhangSan = new User();
		userZhangSan.setUsername("zhangsan");
		userZhangSan.setPassword("123");
		Role role2 = new Role("数据分析员","ROLE_READER");
		role2.getPermissions().add(new Permission("查询权限","find"));
		userZhangSan.getRoles().add(role2);
		userDb.put(userZhangSan.getUsername(),userZhangSan);

		User userLisi = new User();
		userLisi.setUsername("lisi");
		userLisi.setPassword("123");
		Role role3 = new Role("运营管理员","ROLE_OMS");;
		role3.getPermissions().add(new Permission("添加权限","add"));
		role3.getPermissions().add(new Permission("更新权限","update"));
		userLisi.getRoles().add(role3);
		userDb.put(userLisi.getUsername(),userLisi);
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//根据用户标识,从数据库读取用户信息
		User user = userService.findByUserName(username);
		if (user==null){
			return null;
		}
		//将用户的角色和权限封装在list集合中
		List<GrantedAuthority> authorityList= new ArrayList<>();
		for (Role role : user.getRoles()) {//获取用户的角色每个角色信息
			//将用户角色的关键字存入list集合
			authorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
			//获取角色下的每个权限信息
			for (Permission permission : role.getPermissions()) {
				//将权限信息存入到list集合中
				authorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
			}
		}
		//构建UserDetails对象（使用Security框架自动的User类封装），封装用户名、密码（必须是加密过的）及权限角色关键词列表
		String password = user.getPassword();
		//由于数据库中的密码是已经加密的
		//String passwordByaAuth = passwordEncoder.encode(password);//使用bcrypt方式对密码加密
		//创建userdetails对象
		UserDetails userDetails=new org.springframework.security.core.userdetails.User(user.getUsername(),password,authorityList);

		//控制台打印一下数据
		System.out.println("userDetails = " + userDetails);
		System.out.println("password = " + password);
		return userDetails;
	}
}
